<?php
include_once('OAuth.php' );
class WeiboApiFactory  {

	private static $clients = array();
	
	private static function formatPlatform($providor_id){
		$providor_id = trim(ucfirst(strtolower($providor_id)));
		return $providor_id;
	}
	static function client($providor_id, $accecss_token, $accecss_token_secret ){
		if(isset(self::$clients[$providor_id])){
			return self::$clients[$providor_id];
		}
		
		$prefix = self::formatPlatform($providor_id);
		$className = $prefix.'WeiboClient';
//		include_once($prefix.'/'.$className.'.php' );
		$client = new $className($accecss_token, $accecss_token_secret );
		self::$clients[$providor_id] = $client;
		return $client;
	}
	
	static function getWeiboOAuth($providor_id,$withToken = false){

		$accecss_token = NULL;
		$accecss_token_secret = NULL;
		$prefix = self::formatPlatform($providor_id);
		$className = $prefix.'OpenTOAuth';
		$key = 'keys_'.$providor_id; 
		if($withToken && Yii::app()->user->hasState($key)){
			$keys = Yii::app()->user->getState($key);
			$accecss_token = $keys['oauth_token'];
			$accecss_token_secret = $keys['oauth_token_secret'];
		}
		$o = new $className($accecss_token, $accecss_token_secret);
		return $o;
	}
	
	
	static function authorizeURL($providor_id,$source = '/setting/bindResultAccount'){
		$providor_id = self::formatPlatform($providor_id);
		$o = self::getWeiboOAuth($providor_id);
		$keys = $o->getRequestToken();
		$key = 'keys_'.$providor_id;
		Yii::app()->user->setState($key,$keys);
  		$url = $o->getAuthorizeURL($keys['oauth_token'], true, Yii::app()->request->hostInfo . Yii::app()->createUrl($source,array('pid'=>$providor_id)));
 		return $url;
	}
	 
	static function getAccessToken($providor_id,$oauth_verifier){
		$providor_id = self::formatPlatform($providor_id);
		$o = self::getWeiboOAuth($providor_id,true);
		$last_key = $o->getAccessToken( $oauth_verifier ) ;
		return $last_key;
	}
	 
}

?>